//
//  ViewController.swift
//  XNetwork
//
//  Created by anru on 08/07/2024.
//  Copyright (c) 2024 anru. All rights reserved.
//

import UIKit
import XNetwork
import RxSwift

class ViewController: UIViewController {

    private let disposeBag = DisposeBag()
    
    private lazy var startButton: UIButton = {
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
        button.center = view.center
        button.backgroundColor = UIColor.blue
        button.setTitle("Start", for: .normal)
        button.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
        return button
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        connectedToInternet().subscribe(onNext: { [weak self] (connected) in
            print(connected)
        })
        Network.Configuration.default.timeoutInterval = 20
        Network.Configuration.default.plugins = [NetworkIndicatorPlugin()]
        Network.Configuration.default.replacingTask = { target in
            // configure common parameters etc.
            switch target.task {
            case let .requestParameters(parameters, encoding):
                let params: [String: Any] = ["token": "", "sign": "", "body": parameters]
                return .requestParameters(parameters: params, encoding: encoding)
            default:
                return target.task
            }
        }
//        Network.Configuration.default.onSuccess = { response in
//            print(response)
//        }
//        Network.Configuration.default.onError = { error in
//            print("error:\(error)")
//        }
        Network.Configuration.default.addingHeaders = { target in
            if target.path.contains("user") { return ["userId": "123456789"] }
            return [:]
        }
        
        view.addSubview(startButton)
    }
    
    @objc private func startButtonAction() {
        StoryAPI.latest
            .onCache(StoryListModel.self, using: JSONDecoder(), { (model) in
                debugPrint("onCache:", model.topStories.first?.title ?? "")
            })
            .request()
            .subscribe(onSuccess: { (model) in
                debugPrint("onSuccess:", model.topStories.first?.title ?? "")
            })
            .disposed(by: disposeBag)
        
        StoryAPI.latest
            .cache
            .request()
            .map(StoryListModel.self, using: JSONDecoder())
            .subscribe(onNext: { (model) in
                print(model)
            }).disposed(by: disposeBag)
        
        StoryAPI.latest.requset()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

